package org.dromara.system.service.impl;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.system.domain.SkyAbnornal;
import org.dromara.system.domain.SkyPunishment;
import org.dromara.system.domain.bo.ArchivesBo;
import org.dromara.system.utils.SkyEyeClientUtil;
import org.dromara.system.utils.SkyEyeProperties;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.SkyHumanDishonestBo;
import org.dromara.system.domain.vo.SkyHumanDishonestVo;
import org.dromara.system.domain.SkyHumanDishonest;
import org.dromara.system.mapper.SkyHumanDishonestMapper;
import org.dromara.system.service.ISkyHumanDishonestService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 失信被执行人Service业务层处理
 *
 * @author Lion Li
 * @date 2024-09-20
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SkyHumanDishonestServiceImpl implements ISkyHumanDishonestService {

    private final SkyHumanDishonestMapper baseMapper;

    /**
     * 查询失信被执行人
     */
    @Override
    public SkyHumanDishonestVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询失信被执行人列表
     */
    @Override
    public TableDataInfo<SkyHumanDishonestVo> queryPageList(SkyHumanDishonestBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkyHumanDishonest> lqw = buildQueryWrapper(bo);
        Page<SkyHumanDishonestVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询失信被执行人列表
     */
    @Override
    public List<SkyHumanDishonestVo> queryList(SkyHumanDishonestBo bo) {
        LambdaQueryWrapper<SkyHumanDishonest> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkyHumanDishonest> buildQueryWrapper(SkyHumanDishonestBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SkyHumanDishonest> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getBusinessentity()), SkyHumanDishonest::getBusinessentity, bo.getBusinessentity());
        lqw.like(StringUtils.isNotBlank(bo.getAreaname()), SkyHumanDishonest::getAreaname, bo.getAreaname());
        lqw.like(StringUtils.isNotBlank(bo.getCourtname()), SkyHumanDishonest::getCourtname, bo.getCourtname());
        lqw.eq(StringUtils.isNotBlank(bo.getUnperformPart()), SkyHumanDishonest::getUnperformPart, bo.getUnperformPart());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), SkyHumanDishonest::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getPerformedPart()), SkyHumanDishonest::getPerformedPart, bo.getPerformedPart());
        lqw.like(StringUtils.isNotBlank(bo.getIname()), SkyHumanDishonest::getIname, bo.getIname());
        lqw.like(StringUtils.isNotBlank(bo.getDisrupttypename()), SkyHumanDishonest::getDisrupttypename, bo.getDisrupttypename());
        lqw.eq(StringUtils.isNotBlank(bo.getCasecode()), SkyHumanDishonest::getCasecode, bo.getCasecode());
        lqw.eq(StringUtils.isNotBlank(bo.getCardnum()), SkyHumanDishonest::getCardnum, bo.getCardnum());
        lqw.eq(StringUtils.isNotBlank(bo.getPerformance()), SkyHumanDishonest::getPerformance, bo.getPerformance());
        lqw.eq(bo.getRegdate() != null, SkyHumanDishonest::getRegdate, bo.getRegdate());
        lqw.eq(bo.getPublishdate() != null, SkyHumanDishonest::getPublishdate, bo.getPublishdate());
        lqw.eq(StringUtils.isNotBlank(bo.getGistunit()), SkyHumanDishonest::getGistunit, bo.getGistunit());
        lqw.eq(StringUtils.isNotBlank(bo.getDuty()), SkyHumanDishonest::getDuty, bo.getDuty());
        lqw.eq(StringUtils.isNotBlank(bo.getGistid()), SkyHumanDishonest::getGistid, bo.getGistid());
        return lqw;
    }

    /**
     * 新增失信被执行人
     */
    @Override
    public Boolean insertByBo(SkyHumanDishonestBo bo) {
        SkyHumanDishonest add = MapstructUtils.convert(bo, SkyHumanDishonest.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改失信被执行人
     */
    @Override
    public Boolean updateByBo(SkyHumanDishonestBo bo) {
        SkyHumanDishonest update = MapstructUtils.convert(bo, SkyHumanDishonest.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkyHumanDishonest entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除失信被执行人
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void mergeDataByCandidate(String candidate) {
        ArchivesBo bo = new ArchivesBo();
            bo.setName(candidate);

        JSONObject jo = SkyEyeClientUtil.query(bo, SkyEyeProperties.DISHONEST);

        if(!jo.isEmpty() && jo.getInt("total") != 0) {
            ObjectMapper mapper = new ObjectMapper();

            try {
                List<SkyHumanDishonest> list = mapper.readValue(jo.toString(), new TypeReference<>() {});
                //把以前的数据删除
                baseMapper.deleteByCompanies(candidate);
                //重新插入新数据
                list = list.stream().peek(data -> data.setCompanyName(candidate)).toList();
                baseMapper.insertBatch(list);
            } catch (Exception e) {
                log.error("获取失信被执行人数据失败");
            }
        }
    }
}
